import worker from '@ohos.worker';
import socket from '@ohos.net.socket';
import wifiManager from '@ohos.wifiManager';
import {
  dynamicLengthHexIPToHexIP,
  hexIpToDynamicLengthHexIP,
  hexToIp,
  ipToHex,
  ipToStr
} from '../common/NetWork/AddressUtil';
import { GyroscopeControl, Info } from '../common/RemoteControl/GyroscopeControl';
import { Exchange, OperationType } from './WorkerExchange';
import { Address } from '../common/NetWork/BasicNetworkUtil';

const workerPort = worker.workerPort;

let udpSocket: socket.UDPSocket = null;
let gyroscope: GyroscopeControl = null;

let addr: Address = null;

workerPort.onmessage = (event) => {
  let obj = Exchange.fromObject(event.data);
  if (obj != null) {
    if (obj.type == OperationType.create) {
      if (udpSocket == null) {
        udpSocket = socket.constructUDPSocketInstance();
        udpSocket.bind({ address: ipToStr(wifiManager.getIpInfo().ipAddress), family: 1 }).then(() => {
          console.log("bind success")
        }, () => {
          console.log("bind failed");
        });
      }
    } else if (obj.type == OperationType.startGyroscope) {
      if (gyroscope == null) {
        gyroscope = new GyroscopeControl(1e5);
      }
      gyroscope.setCallback((data: Info) => {
        if (addr != null) {
          udpSocket.send({ address: { address: addr.ip, port: addr.port, family: 1 }, data: data.encode() });
        }
        workerPort.postMessage(data.toObject());
      })
    } else if (obj.type == OperationType.stopGyroscope) {
      gyroscope.close();
      gyroscope = null;
    }
    else if (obj.type == OperationType.setAddress) {
      addr = new Address();
      addr.ip = obj.ip;
      addr.port = obj.port;
    }
  }
}
